//
//  DatePickerViewController.swift
//  DemoProject
//
//  Created by hao on 2018/7/18.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit

class DatePickerViewController: BaseTableViewController {

    let disposeBag = DisposeBag()
    
    lazy var datePicker: UIDatePicker = {
        let _datePicker = UIDatePicker()
        self.tableHeadView.addSubview(_datePicker)
        _datePicker.snp.makeConstraints({ (make) in
            make.center.equalTo(self.tableHeadView)
        })
        return _datePicker
    }()
    
    lazy var label: UILabel = {
        let _label = UILabel()
        self.tableHeadView.addSubview(_label)
        _label.snp.makeConstraints({ (make) in
            make.centerX.equalTo(self.tableHeadView)
            make.bottom.equalTo(datePicker.snp.top).offset(-20)
        })
        return _label
    }()
    
    // 开始倒计时的按钮
    lazy var startBtn: UIButton = {
        let _start = UIButton(type: .system)
        self.tableHeadView.addSubview(_start)
        _start.setTitle("开始倒计时", for: .normal)
        _start.snp.makeConstraints({ (make) in
            make.centerX.equalTo(self.tableHeadView)
            make.top.equalTo(datePicker.snp.bottom).offset(20)
        })
        return _start
    }()
    
    //剩余时间（必须为 60 的整数倍，比如设置为100，值自动变为 60）
    let leftTime = Variable(TimeInterval(60))
    //当前倒计时是否结束
    let countDownStopped = Variable(true)
    
    //日期格式化
    lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
        return formatter
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
//        _rxProperty()
        _countDown()
    }
    
    /// UIDatePicker 设置倒计时
    private func _countDown() {
        DispatchQueue.main.async {
        }
        // 双向绑定 剩余时间与datepicker
        _ = self.datePicker.rx.countDownDuration <-> self.leftTime
        
        // 绑定button标题
        Observable.combineLatest(leftTime.asObservable(), countDownStopped.asObservable()) { (time, isStop) -> String in
            //根据当前的状态设置按钮的标题
            if isStop {
                return "开始"
            } else {
                return "倒计时开始，还有 \(Int(time)) 秒..."
            }
        }.bind(to: label.rx.text).disposed(by: disposeBag)
        
        //绑定button和datepicker状态（在倒计过程中，按钮和时间选择组件不可用）
        countDownStopped.asDriver().drive(datePicker.rx.isEnabled).disposed(by: disposeBag)
        countDownStopped.asDriver().drive(startBtn.rx.isEnabled).disposed(by: disposeBag)
        
        //按钮点击响应
        startBtn.rx.tap .bind { [weak self] in
                self?.startClicked()
            }.disposed(by: disposeBag)
        
    }
    
    private func startClicked() {
        //开始倒计时
        self.countDownStopped.value = false
        
        //创建一个计时器
        Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            // takeUntil: 监听 countDownStopped observable
            .takeUntil(countDownStopped.asObservable().filter{ $0 }) //倒计时结束时停止计时器
            .observeOn(MainScheduler.asyncInstance)
            .subscribe { [weak self] event in
                //每次剩余时间减1
                self?.leftTime.value -= 1
                // 如果剩余时间小于等于0
                if(self?.leftTime.value == 0) {
                    print(info: "倒计时结束")
                    //结束倒计时
                    self?.countDownStopped.value = true
                    //重制时间
                    self?.leftTime.value = 60
                }
            }.disposed(by: disposeBag)
    }
    
    private func _rxProperty() {
        datePicker.rx.date.map { [weak self] in
            "当前选择时间为: " + self!.dateFormatter.string(from: $0)
        }.bind(to: label.rx.text).disposed(by: disposeBag)
    }
    
    private func setupData() {
        let titles = ["日期选择器区域设置为中文",
                      "添加监听时间的改变",
                      "改变控件时间选择模式",
                      "修改文字颜色",
                      "设置DatePicker的时区",
                      "设置DatePicker的日期",
                      "minimumDate",
                      "maximumDate",
                      "countDownDuration"]
        
        let descArr = ["datePicker.locale = Locale(identifier: \"zh_CN\")",
                       """
                        datePicker.addTarget(self, action: #selector(dateChanged),
                             for: .valueChanged)
                       """,
                       """
                        // 只有日期选择
                        datePicker.datePickerMode = .date
                        // 只有时间选择
                        datePicker.datePickerMode = .time
                       """,
                       """
                        datePicker.setValue(UIColor.white, forKey: "textColor")
                       """,
                       "[datePicker setTimeZone:[NSTimeZone defaultTimeZone]];",
                       "[datePicker setDate:[NSDate date]];",
                       "设置DatePicker的允许的最小日期",
                       "设置DatePicker的允许的最大日期",
                       """
                        设置DatePicker的倒计时间.
                        // 1) 设置日期选择的模
                        [self.datePicker setDatePickerMode:UIDatePickerModeCountDownTimer];

                        // 2) 设置倒计时的时长
                        // 注意：设置倒计时时长需要在确定模式之后指定
                        // 倒计时的时长，以秒为单位
                        [self.datePicker setCountDownDuration:10 * 60];
                       """]
        
        addTitles(titles, footDescs: descArr)
    }

}
